package com.fingard.dsp.bank.directbank.aibank01;

import java.math.BigDecimal;
import java.sql.Connection;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

import com.alibaba.fastjson.JSON;
import com.fingard.FGBiz;
import com.fingard.constant.Format;
import com.fingard.db.JDBCHelper;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.fingard.dsp.bank.directbank.aibank01.request.SendRequest;
import com.fingard.dsp.bank.directbank.bankInterface.ISinglePay;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqQrySingleBat;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingle;
import com.fingard.dsp.bank.reqrespobj.single.ReqSingleBat;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingle;
import com.fingard.dsp.bank.reqrespobj.single.RetAtsSingleBat;
import com.fingard.dsp.bank.reqrespobj.single.detail.RetAtsSglDetail;
import com.kayak.request.PaymentRequest;
import com.kayak.request.SinTranStuRequest;
import com.kayak.response.PaymentResponse;
import com.kayak.response.SinTranStuResponse;

public class AIBANK01SinglePay extends AIBANK01Base implements ISinglePay {

	@Override
	/** 单笔支付 */
	public RetAtsSingle d_1908_SglPay(ReqSingle p_req1908) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req1908.reqHeader);
		RetAtsSglDetail detail = new RetAtsSglDetail();
		try {
			detail.reqSeqID = p_req1908.singleDetail.askNumber;
			ApplicationContext ac = new ClassPathXmlApplicationContext("classpath*:dsp-config/spring-config.xml");
			SendRequest sendRequest = (SendRequest) ac.getBean("SendRequest");
			// 构建支付model
			PaymentRequest paymentRequest = new PaymentRequest();
			paymentRequest.setVersion(getBankConfig().getValueAsString("version")); // 版本号
			paymentRequest.setMchtNo(bankFront.corpNo); // 商户号
			paymentRequest.setSubMchtNo(getBankConfig().getValueAsString("subMchtNo"));// 二级商户号
			paymentRequest.setProductNo(bankFront.org);// 产品号
			paymentRequest.setBizType(getBankConfig().getValueAsString("bizType"));// 业务类型
			paymentRequest.setContractNo(p_req1908.singleDetail.askNumber);// 渠道流水号
			paymentRequest.setPayerAcctNo(p_req1908.singleDetail.payAct);// 付款人账号
			paymentRequest.setPayerAcctName(p_req1908.singleDetail.payName);// 付款人账号
			if(p_req1908.singleDetail.payBankName!=null && p_req1908.singleDetail.payBankName.contains("百信")){
				paymentRequest.setPayerOpBankCode("326100010008");// 付款人开户行行号 p_req1908.singleDetail.payBankCode
			}
			paymentRequest.setSrcOfFund("");// 资金来源 00:一般性付款 01:个人账户付款 02:现金付款03:营销返现04:特定商户结算05:农资收购06:跨境退税07:跨境汇款// 08-99:保留使用
			paymentRequest.setTranType("1");// 交易类型 1:客户发起 2:金融机构发起
			paymentRequest.setCnapsBizType("A100");// 二代业务类型 默认为A100
			paymentRequest.setPriority("");// 优先级别 默认为3 1：特急 2：紧急3：普通
			paymentRequest.setSyscode("");// 汇路 (取配置文件)
			paymentRequest.setPayeeBankCode(p_req1908.singleDetail.cnapsCode); // 收款行行号
			paymentRequest.setPayeeAcctNo(p_req1908.singleDetail.recAct);// 收款人账户
			paymentRequest.setPayeeAcctName(p_req1908.singleDetail.recName);
			if(p_req1908.singleDetail.isPrivate.equals("1")){
				paymentRequest.setPayeeAcctType("DEBIT");// 收款人账户类型 CREDIT:贷记卡 DEBIT:借记卡 PUBLIC:对公账户
			}else{
				paymentRequest.setPayeeAcctType("PUBLIC");// 收款人账户类型 CREDIT:贷记卡 DEBIT:借记卡 PUBLIC:对公账户
				paymentRequest.setPayeeOpBankCode(p_req1908.singleDetail.cnapsCode);
			}
			paymentRequest.setPayeeOpBankName(p_req1908.singleDetail.recBankName);// 开户行名称
			String ccy =convertCurToBank(p_req1908.singleDetail.payCur);
			paymentRequest.setCcy(ccy);// 币种
			paymentRequest.setAmt(new BigDecimal(p_req1908.singleDetail.payAmount));// 金额
			paymentRequest.setRemark(p_req1908.singleDetail.memo);// 备注
			paymentRequest.setRemark1(p_req1908.singleDetail.description);// 描述
			WriteBankLogLn("请求的对象参数" + JSON.toJSONString(paymentRequest));
			// 发送银行
			PaymentResponse resp = sendRequest.sendToBank(paymentRequest);
			WriteBankLogLn("返回的对象结果" + JSON.toJSONString(resp));
			if (resp != null) {
				String tmpRetCode = resp.getReturnCode();
				String tmpRetInfo = resp.getReturnMessage();
				String dealResult = resp.getDealResult();
				if (!dealResult.equals("FAIL")) {
					if (!dealResult.equals("FAIL")) {
						Connection conn = FGBiz.getLocalDbConn();
						detail.respCode = "0";
						detail.respInfo = tmpRetInfo;
						detail.payInfoCode = tmpRetCode + "+"+dealResult;
						detail.transState = tmpRetCode+"+"+dealResult;
						detail.transAmt = p_req1908.singleDetail.payAmount;
						String uuid = UUID.randomUUID().toString().replaceAll("-", "");
						String tranNo = paymentRequest.getTranNo() +"@"+paymentRequest.getHead().getSubTransSeq();
						JDBCHelper.update(conn, INSERTSEQ, new Object[]{uuid, p_req1908.reqHeader.bankCode, Format.Date8Format.format(new Date()), p_req1908.reqHeader.reqSeqID, tranNo});
						retAts.writeRetDetail(detail);
					} else {
						retAts.writeStart();
						retAts.writeRespCode("-1");
						retAts.writeRespInfo(tmpRetInfo);
					}
				} else {
					detail.payInfoCode = tmpRetCode + "+"+dealResult;
					detail.transState = tmpRetCode+"+"+dealResult;
					retAts.writeStart();
					retAts.writeRespCode("-1");
					retAts.writeRespInfo(tmpRetInfo.toString());
				}
			} else {
				retAts.writeStart();
				retAts.writeRespCode("-1");
				retAts.writeRespInfo("交易失败");
			}
		} catch (Exception e) {
			retAts.writeRespCode("-1");
			retAts.writeRespInfo(e.getMessage());
			e.printStackTrace();
			WriteBankLogLn("交易出现异常:" + e);
		}
		retAts.writeEnd();
		return retAts;
	}

	@Override
	public RetAtsSingleBat d_1908BAT_SglBatPay(ReqSingleBat p_req1908BAT) throws Exception {
		return null;
	}

	@Override
	/**
	 * 支付状态查询
	 */
	public RetAtsSingle d_1944_QrySglPay(ReqQrySingle p_req1944) throws Exception {
		RetAtsSingle retAts = new RetAtsSingle(p_req1944.reqHeader);
		RetAtsSglDetail detail = new RetAtsSglDetail();
		ApplicationContext ac = new ClassPathXmlApplicationContext("classpath*:dsp-config/spring-config.xml");
		SendRequest client1 = (SendRequest) ac.getBean("SendRequest");
		Connection conn = FGBiz.getLocalDbConn();
		String tranNo = "";
		String orgTranNo = "";
		Map<String, Object> selMap = JDBCHelper.execQuerySingle(conn, SELECTSEQ, new Object[]{p_req1944.reqHeader.reqSeqID, p_req1944.reqHeader.bankCode});
		if(selMap!=null){
			WriteBankLogLn("文件数据库获取到的值为："+JSON.toJSONString(selMap));
			if(selMap.get("BANKREQSEQID")==null){
				WriteBankLogLn("未获取到请求映射流水号"+p_req1944.reqHeader.reqSeqID);
				detail.respCode = "-1";
				detail.respInfo = "未获取到请求映射流水号"+p_req1944.reqHeader.reqSeqID;
				retAts.writeRetDetail(detail);
				return retAts;
			}
			String str = selMap.get("BANKREQSEQID").toString();
			if(str!=null){
				tranNo = str.split("@")[0];
				orgTranNo = str.split("@")[1];
			}
			WriteBankLogLn("映射核心流水号为："+str);
		}
		// 构建交易状态查询MODEL
		SinTranStuRequest tranStuRequest = new SinTranStuRequest();
		tranStuRequest.setVersion(getBankConfig().getValueAsString("version"));
		tranStuRequest.setMchtNo(bankFront.corpNo);// 商户号 (渠道配置)
		tranStuRequest.setSubMchtNo(getBankConfig().getValueAsString("subMchtNo"));// 二级商户号
		tranStuRequest.setOrgTranNo(tranNo);// 原交易渠道交易序号
		tranStuRequest.setOrgSubTransSeqIn(orgTranNo);// 原交易子交易序号s
		tranStuRequest.setBizType("01");// 业务类型
		WriteBankLogLn("发送的参数为："+JSON.toJSONString(tranStuRequest));
		SinTranStuResponse stuResp = client1.sendToBank(tranStuRequest);
		WriteBankLogLn("获取到的结果为："+JSON.toJSONString(stuResp));
		if (stuResp != null) {
			String tmpRetCode = stuResp.getReturnCode();
			String tmpRetInfo = stuResp.getReturnMessage();
			if (tmpRetCode.equals("BBLUPP00000")) {
				String dealResult = stuResp.getDealResult();
				if (!dealResult.equals("FAIL")) {
					detail.respCode = "0";
					detail.respInfo = tmpRetInfo;
					detail.payInfoCode = tmpRetCode + "+" + stuResp.getDealResult();
					detail.reqSeqID = p_req1944.reqHeader.reqSeqID;
					detail.transState = tmpRetCode + "+" + stuResp.getDealResult();
					detail.transAmt = p_req1944.payAmount;
					retAts.writeRetDetail(detail);
				} else {
					detail.respCode = "-1";
					detail.respInfo = tmpRetInfo;
					detail.payInfoCode = tmpRetCode + "+" + stuResp.getDealResult();
					detail.reqSeqID = p_req1944.reqHeader.reqSeqID;
					detail.transState = tmpRetCode + "+" + stuResp.getDealResult();
					retAts.writeRetDetail(detail);
				}
			} else {
				detail.respCode = "-1";
				detail.respInfo = tmpRetInfo.toString();
				retAts.writeRetDetail(detail);
			}
		} else {
			detail.respCode = "-1";
			detail.respInfo = "请求失败";
			retAts.writeRetDetail(detail);
		}
		return retAts;
	}

	@Override
	public RetAtsSingleBat d_1944BAT_QrySglBatPay(ReqQrySingleBat p_req1944BAT) throws Exception {
		return null;
	}
}
